package com.lym.reggie.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lym.reggie.common.R;
import com.lym.reggie.entity.Category;
import com.lym.reggie.entity.Dish;
import com.lym.reggie.entity.DishDto;
import com.lym.reggie.entity.DishFlavor;
import com.lym.reggie.service.CategoryService;
import com.lym.reggie.service.DishFlavorService;
import com.lym.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        // 新增菜品
        log.info("dishDto:{}", dishDto);

        dishService.saveWithFlavor(dishDto);
        //需清理缓存 保证数据库的数据与缓存中的数据一致
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("name: {}",name);
      // 1. Dish分页查询
        //1.1 构造一个分页构造器对象
        Page<Dish> dishPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage,queryWrapper);

        Page<DishDto> dishDtoPage = new Page<>();
      //   2. 对象拷贝：使用框架自带的工具类，第三个参数是不拷贝到属性 records属性是分页插件中表示分页中所有的数据的一个集合
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        // 2.1 处理 再进行拷贝
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtoList = records.stream().map(item->{
            DishDto dishDto = new DishDto();
            // 2.2 拷贝
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                //2.3 设置实体类DishDto的categoryName属性值
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //  3. 重新设置records属性值
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    //查询菜品  数据回显
    @GetMapping("/{id}")
    public R<DishDto> edit(@PathVariable long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改菜品
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        //需清理缓存 保证数据库的数据与缓存中的数据一致
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }
    //启售 停售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status,@RequestParam List<Long> ids){

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids!=null,Dish::getId,ids);
        List<Dish> dishList = dishService.list(queryWrapper);
        for (Dish dish : dishList) {
            if (dish!=null){
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        if (status==0){
            return R.success("开始禁售！");
        }else {
            return R.success("开始启售！");
        }
    }

    //删除菜品
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids: {}",ids);
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");

    }

    //根据菜品分类id 查询菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info("categoryId: {}",dish.getCategoryId());

        List<DishDto> dishDtoList = null;
        //1。查看是否有Redis缓存
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //有缓存，则直接返回结果
        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }
        //2。没有，查询数据库、将查询到的菜品数据放入Redis
        //2.1 查询数据库
        Long categoryId = dish.getCategoryId();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.eq(Dish::getStatus,dish.getStatus());
        //增加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);
        //查询对应口味
        dishDtoList = dishList.stream().map(dishItem->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishItem,dishDto);

            Long dishId = dishItem.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
            dishFlavorWrapper.eq(dishId!=null,DishFlavor::getDishId,dishId);
            List<DishFlavor> flavors = dishFlavorService.list(dishFlavorWrapper);

            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());

        //2.2 将查询到的菜品数据放入Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }


}
